import { io } from 'socket.io-client';

class SocketService {
  constructor() {
    this.socket = null;
    this.handlers = new Map();
    this.currentRoom = null;
  }

  connect() {
    this.socket = io('http://localhost:3001', {
      withCredentials: true,
      transports: ['websocket', 'polling']
    });

    this.socket.on('connect', () => {
      console.log('已连接到服务器');
      // 如果有当前房间，重新加入
      if (this.currentRoom) {
        this.joinRoom(this.currentRoom.userData, this.currentRoom.room);
      }
    });

    this.socket.on('connect_error', (error) => {
      console.error('连接错误:', error);
    });

    this.socket.on('disconnect', () => {
      console.log('与服务器断开连接');
    });

    // 注册基本事件监听器
    this.registerBaseHandlers();
  }

  registerBaseHandlers() {
    // 消息发送确认
    this.socket.on('message_sent', (data) => {
      this.triggerHandler('message_sent', data);
    });

    // 接收新消息
    this.socket.on('new_message', (data) => {
      this.triggerHandler('new_message', data);
    });

    // 消息状态更新
    this.socket.on('message_status_update', (data) => {
      this.triggerHandler('message_status_update', data);
    });

    // 在线用户列表更新
    this.socket.on('user_list', (data) => {
      this.triggerHandler('user_list', data);
    });
  }

  // 注册事件处理器
  on(event, handler) {
    if (!this.handlers.has(event)) {
      this.handlers.set(event, []);
    }
    this.handlers.get(event).push(handler);
  }

  // 移除事件处理器
  off(event, handler) {
    if (!this.handlers.has(event)) return;
    const handlers = this.handlers.get(event);
    const index = handlers.indexOf(handler);
    if (index !== -1) {
      handlers.splice(index, 1);
    }
  }

  // 触发事件处理器
  triggerHandler(event, data) {
    if (!this.handlers.has(event)) return;
    this.handlers.get(event).forEach(handler => handler(data));
  }

  // 加入房间
  joinRoom(userData, room) {
    if (this.socket) {
      this.currentRoom = { userData, room };
      this.socket.emit('join_room', { userData, room });
    }
  }

  // 离开房间
  leaveRoom() {
    if (this.socket && this.currentRoom) {
      this.socket.emit('leave_room', this.currentRoom.room);
      this.currentRoom = null;
    }
  }

  // 发送房间消息
  sendMessage(message) {
    if (this.socket && this.currentRoom) {
      this.socket.emit('room_message', {
        room: this.currentRoom.room,
        message
      });
    }
  }

  // 标记消息为已读
  markMessagesAsRead(messageIds) {
    if (this.socket && this.currentRoom) {
      this.socket.emit('message_read', {
        room: this.currentRoom.room,
        messageIds
      });
    }
  }

  // 断开连接
  disconnect() {
    if (this.socket) {
      if (this.currentRoom) {
        this.leaveRoom();
      }
      this.socket.disconnect();
      this.socket = null;
    }
  }

  // 检查连接状态
  isConnected() {
    return this.socket && this.socket.connected;
  }

  // 获取当前房间信息
  getCurrentRoom() {
    return this.currentRoom;
  }
}

// 创建单例实例
const socketService = new SocketService();
export default socketService;